package com.wangbaokang.duanxin.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class DbUtils {

	private static DbUtils instance;
	
	private DbUtils(Context ctx){
		dbHelper = new MySliteHelper(ctx, "itheima33", 1);
		this.ctx = ctx;
	}
	
	private MySliteHelper dbHelper;
	
	private Context ctx;
	
	public static synchronized DbUtils getInstance(Context ctx){
		if(instance == null){
			instance = new DbUtils(ctx);
			
		}
		return instance;
	}

	/**
	 * Ⱥ��ı���
	 */
	public static final String TABLE_GROUPS ="groups";
	/**
	 * �Ự��Ⱥ���Ӧ��ϵ ���� 
	 */
	public static final String TABLE_THREAD_GROUPS ="thread_groups";

	/**
	 * ����cursor�����URI
	 */
	private static final Uri URI_NOTIFY = Uri.parse("content://www.itheima.com");
	

	/**
	 * ���Ⱥ��
	 * @param name Ⱥ�����
	 */
	public void createGroup(String name) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("name", name);
		
		db.insert(TABLE_GROUPS, "_id", values);
		notifyUri();
	}

	private void notifyUri() {
		ctx.getContentResolver().notifyChange(URI_NOTIFY, null);
	}

	/**
	 * ��ѯȺ��?����cursor
	 * @return
	 */
	public Cursor getAllGroup() {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(TABLE_GROUPS, null, null, null, null, null, null);
		cursor.setNotificationUri(ctx.getContentResolver(), URI_NOTIFY);
		System.out.println(cursor);
		return cursor;
	}

	/**
	 * ɾ��ָ����Ⱥ��
	 * @param groupId Ⱥ���IDֵ
	 */
	public void deleteGroupById(int groupId) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		db.delete(TABLE_GROUPS, "_id = "+groupId, null);
		
		//����֪ͨ���������
		notifyUri();
	}

	/**
	 * ����ָ��Ⱥ������
	 * @param groupId	Ⱥ��ID
	 * @param name	�µ����
	 */
	public void updateGroupNameById(int groupId, String name) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("name", name);
		
		db.update(TABLE_GROUPS, values, "_id = "+groupId, null);
		
		notifyUri();
	}

	/**
	 	���ỰID���Ӧ��Ⱥ��ID����������ỰȺ���Ӧ��ϵ��
	 * @param threadId  �ỰID
	 * @param selectGroupId  Ⱥ��ID
	 */
	public void addThreadGroupValue(int threadId, int selectGroupId) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("thread_id", threadId);
		values.put("group_id", selectGroupId);
		db.insert(TABLE_THREAD_GROUPS, "_id", values);
		
	}

	/**
	 * ��ѯ�ỰȺ���Ӧ��ϵ�?���ذ���Ӧ�ĻỰID��cursor
	 * @param groupId
	 * @return
	 */
	public Cursor getThradIdByGroupId(int groupId) {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		
		Cursor query = db.query(TABLE_THREAD_GROUPS, null, "group_id = "+groupId, null, null, null, null);
		
		return query;
	}
}
